<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in orderStatus_data"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入系统订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="批次号" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="充值账号" prop="account">
        <el-input
          v-model="queryParams.account"
          placeholder="请输入充值账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="下单时间" prop="creatTime">
        <el-date-picker
          clearable
          v-model="queryTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          placeholder="请选择下单时间"
          @change="handleDatePickerChange">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--导出-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="queryQSFromToExport"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="formList" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="充值号码" align="center" prop="account" />
      <el-table-column label="商品编码" align="center" prop="productId" />
      <el-table-column label="全时订单号" align="center" prop="qsOrderNo" />
      <el-table-column
        label="下单数量"
        align="center"
        prop="count"
        :formatter="countFormatter"
      />
      <el-table-column label="下单时间" align="center" prop="creatTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.creatTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>


      <el-table-column label="订单状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span :style="{ color: getStatusColor(scope.row.orderStatus) }">{{statusFormatter(scope.row.orderStatus)}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-detail"
            @click="handleDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="queryQSFrom"
    />

    <!-- 详情对话框 -->
    <el-dialog :title="title" :visible.sync="openDetail" width="950px" append-to-body>
      <el-table :data="DetailData">
        <el-table-column label="券码" align="center" prop="couponCode"/>
        <el-table-column label="开始时间" align="center" prop="startTime"/>
        <el-table-column label="过期时间" align="center" prop="expireTime" />

        <el-table-column label="优惠券状态" align="center" prop="couponStatus" >
          <template slot-scope="scope">
            <span :style="{ color: getCouponStatusColor(scope.row.couponStatus) }">{{couponStatusFormatter(scope.row.couponStatus)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="券核销流水号" align="center" prop="sno" />
        <el-table-column label="使用时间" align="center" prop="useTime" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-detail"
              @click="pushUse(scope.row)"
            >推送核销</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="detailSubmit">确 定</el-button>
        <el-button @click="detailCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "Form",
  dicts: ['from_status'],
  data() {
    return {
      // 最终展示的图片数组
      orderStatus_data:[
        {value:"FAIL",label:"失败"},
        {value:"SUCCESS",label:"成功"},
        {value:"IN_PROCESS",label:"处理中"},
      ],
      name_data:[
        {value:"11",label:"未使用"},
        {value:"12",label:"已锁定"},
        {value:"13",label:"已核销"},
        {value:"14",label:"已作废"},
      ],
      queryTime: null,
      openDetail: false,
      detailForm: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],

      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      formList: [],
      DetailData:[],
      exportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId:null,
        orderStatus:null,
        orderNo: null,
        account: null,
        startTime: null,
        endTime:null,
      },
      // 表单参数
      form: {},
      couponRequest:{
        orderNo:null,
        couponCode:null,
      },
      // 表单校验
      rules: {
      },
      img:{},
    };
  },
  created() {
    this.queryQSFrom();
  },
  methods: {

    countFormatter(row, column, cellValue) {
      // 如果值为空或null，返回默认值1，否则返回原值
      return cellValue == null || cellValue === '' ? 1 : cellValue;
    },
    getStatusColor(status) {
      switch (status) {
        case "IN_PROCESS":
          return 'blue';
        case "FAIL":
          return 'red';
        case "SUCCESS":
          return 'green';
      }
    },
    getCouponStatusColor(status) {
      switch (status) {
        case 11:
          return 'blue';
        case 12:
          return 'red';
        case 14:
          return 'red';
        case 13:
          return 'green';
      }
    },
    couponStatusFormatter(status) {
      // 根据 cellValue 的值返回相应的中文描述
      switch (status) {
        case 11:
          return '未使用';
        case 12:
          return '已锁定';
        case 13:
          return '已核销';
        case 14:
          return '已作废';
      }
    },



    statusFormatter(status) {
      // 根据 cellValue 的值返回相应的中文描述
      switch (status) {
        case "IN_PROCESS":
          return '充值中';
        case "FAIL":
          return '失败';
        case "SUCCESS":
          return '充值成功';
      }
    },


    timeFormatter(row, column, cellValue) {
      const date = new Date(cellValue);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    handleDatePickerChange(value) {
      if (value == null){
        this.queryParams.startTime =null;
        this.queryParams.endTime =null;
      } else {
        this.queryParams.startTime =value[0];
        this.queryParams.endTime =value[1];
      }
    },


    // 确定 detailSubmit
    detailSubmit() {
      this.openDetail = false;
      this.reset();
    },
    // 取消按钮
    detailCancel() {
      this.openDetail = false;
      this.reset();
    },
    /** 查询订单列表 */
    queryQSFrom(){
      this.loading = true;
      axios.post('http://47.110.49.47:8077/api/okr/querySharingOrder', this.queryParams)
        .then(res => {
          if (res.data.code === "200"){
            console.log(res.data.encryptData.data)
            this.formList = res.data.encryptData.data;
            this.total = res.data.encryptData.total;
          }
          this.loading = false;
          // 根据需要处理响应数据
        })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderStatus:null,
        productId:null,
        orderNo: null,
        account: null,
        startTime: null,
        endTime:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryQSFrom();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 查看单行详情 */
    handleDetail(row){
      this.reset();
      const id = row.id || this.ids
      axios.get('http://47.110.49.47:8077/api/okr/querySharingCoupon/'+id)
        .then(res => {
          if (res.data.code === "200"){
            this.DetailData = res.data.encryptData? res.data.encryptData:[];
          }
          this.openDetail = true;
          this.title = "券码详情";
        })
    },

    /** 推送核销 */
    pushUse(row){
      this.reset();
      this.couponRequest.orderNo = row.orderNo
      this.couponRequest.couponCode = row.couponCode
      axios.post('http://47.110.49.47:8077/api/okr/pushUseCoupon',this.couponRequest)
        .then(res => {
          if (res.data.code === "200"){
            this.$modal.msgSuccess("提交成功");
          }else {
            this.$modal.msgError("推送失败");
          }
        }).catch(error=>{
        this.$modal.msgError("推送失败");
      })
    },


    /** 导出按钮操作 */
    handleExport() {
        //alert("测试中");
       /* return ;*/
        this.$confirm('是否确认导出？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.queryQSFromToExport();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消导出操作'
          });
        });
    },
    /*127.0.0.1*/
    queryQSFromToExport() {
      this.loading = true;
      axios.post(
        'http://47.110.49.47:8077/api/okr/couponStatusExport',
        this.queryParams,
        {
          responseType: 'blob', // 确保接收的是二进制数据
        }).then(res => {
          // 检查响应状态或数据（后端可以返回状态码或标志位）
          if (!res || res.status !== 200) {
            this.$modal.msgError("导出失败！");
            this.loading = false;
            return;
          }
          // 创建 Blob 对象
          const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          // 创建下载链接
          const a = document.createElement('a');
          const href = window.URL.createObjectURL(blob);
          a.href = href;
          // 设置文件名（处理中文转码）
          const fileName = decodeURIComponent('导出.xlsx'); // 根据实际文件名设置
          a.download = fileName;

          // 触发下载
          document.body.appendChild(a);
          a.click();

          // 清理 DOM 和 URL 对象
          document.body.removeChild(a);
          window.URL.revokeObjectURL(href);

          this.loading = false;
        })
        .catch(err => {
          console.error("导出失败：", err);
          this.$modal.msgError("导出失败，请稍后重试！");
          this.loading = false;
        });
    }


    // deriveExcel(){
    //   let opt = {
    //     url: "Common/deriveExcel",
    //     method: 'get',
    //     responseType: 'blob',
    //     data: this.AccessDataManager
    //   }
    //   this.$axios.request(opt).then(res => {
    //     if (!res) return
    //     const blob = new Blob([res.data], {type: 'application/vnd.ms-excel;'})
    //     const a = document.createElement('a');
    //     // 生成文件路径
    //     let href = window.URL.createObjectURL(blob)
    //     a.href = href
    //     //文件名中有中文 则对文件名进行转码
    //     a.download = decodeURIComponent('导出');
    //     //利用a标签做下载
    //     document.body.appendChild(a)
    //     a.click()
    //     document.body.removeChild(a)
    //     window.URL.revokeObjectURL(href)
    //     this.allloading = false;
    //   })
    // },



  }
};
</script>

<style>
.image-container {
  display: flex;
}

.custom-image {
  width: 100px; /* 调整图片宽度 */
  height: 100px; /* 调整图片高度 */
  margin-right: 10px; /* 可选：设置图片之间的右边距，使它们之间有间隙 */
}
</style>
